const express = require("express")
const studentRouter = express.Router();
const {getStudentById,getStudents,updateStudent,delStudent,getStudentsWithTotal,addStudent}=require("../services/studentService");
const {returnData,handleAsyncError} = require("../utils/returnMsg")
var qs = require('qs');
// const { async } = require("validate.js");
const student = require("../models/student");
// const { async } = require("validate.js");
studentRouter.get('/',async (req,res)=>{
    // console.log(req.baseUrl,"基地址") // /api/student
    // console.log(req.path,'请求路径') // /
    // 分页请求学生
    // console.log('1',req.query)
    const target = qs.parse(req.query)
    console.log(target)
    const page = +req.query.page || 1;
    const size = +req.query.size || 10;
    let sex
    if(req.query.sex==='男'){
        sex = true
    }else if(req.query.sex==='女'){
        sex = false
    }
    const GradeId = +req.query.GradeId || -1;
    // // console.log(page,size,sex,GradeId)
    // console.log(typeof req.query.page,typeof req.query.size)
    const resp =  await getStudentsWithTotal(page,size,sex,GradeId)
    res.send(returnData(resp));
})

studentRouter.get('/:id',async (req,res)=>{
    // console.log(req.baseUrl,"基地址") // /api/student
    // console.log(req.path,'请求路径') // /
    // 请求单个学生
    // console.log('2',req.params)
    
    const id = req.params.id;
    const resp = await getStudentById(id);
    res.send(returnData(resp));

})

// studentRouter.post('/',async (req,res)=>{
//     // 添加一个学生
//     console.log(req.body)
//     // const resp = await addStudent(req.body)
//     // console.log()
//     // 如果是一个异步函数进行报错 就需要包装一下
    
//     throw 123
// })

studentRouter.post('/',handleAsyncError(async (req,res,next)=>{
    const resp = await addStudent(req.body);
    return resp
    
}))

studentRouter.delete('/:id',handleAsyncError(async (req,res,next)=>{
    const resp = await delStudent(req.params.id);
    return resp
    
}))
// 修改某个学生
studentRouter.put('/:id',handleAsyncError(async (req,res,next)=>{
    const resp = await updateStudent(req.params.id,req.body);
    return resp
    
}))
// 一个使用jsonp的接口
studentRouter.get("/jsonpData/:id",async(req,res,next)=>{
    // 当前资源以jsonp的形式给与前端
    const resp = await getStudentsWithTotal();
    const tar = JSON.stringify(resp)
    const script = `
    jsonp(${tar})
    `
    res.header("content-type","application/javascript").send(script)
})
module.exports = studentRouter